import axios from "axios"



const baseUrl="http://127.0.0.1:8000";

const ajaxs = axios.create({
    baseURL:baseUrl,
    timeout:5000,
    headers:{
        Authorization:`Bearer ${localStorage.getItem('token')}`
    }
})

//axios.defaults.headers.head.Authorization = localStorage.getItem('token');
// 如果需要跨域，可以设置 withCredentials 为 true
//axios.defaults.withCredentials = true // 允许跨域请求发送 cookies

// 创建 axios 实例
//const service = axios.create({
//    timeout:10000
//})
let isRefresh = false
let request_list:any[] = []
// 请求拦截器
ajaxs.interceptors.request.use(config => {
    const token = 'Bearer '+localStorage.getItem('token') // store.state.token
    token && (config.headers.Authorization = token);
    return config;
    },
    error => {
        return Promise.reject(error);

})
// 响应拦截器
ajaxs.interceptors.response.use(
    response => {
        return Promise.resolve(response)
}, async(error) => {
    console.log(error)
    if(error.status===401 && request_list.length<5){
        if(!isRefresh){
            isRefresh=true
            localStorage.setItem("token",localStorage.getItem("refreshtoken")||"")
            let result:any = await ajax("GET","/refreshtoken")
            console.log("刷新token：" ,result)

            localStorage.setItem("token",result.data[0].token||"")
            localStorage.setItem("refreshtoken",result.data[0].refreshtoken||"")
            //console.log(error)
            //let agian = await ajaxs(error.config)
            request_list.forEach((item:any) => item())
            let agian = await ajaxs(error.config)
            isRefresh=false
            request_list = []
            return Promise.resolve(agian)
        }else{
            return new Promise(resove => {
                request_list.push(() => {
                    resove(ajaxs(error.config))
                })
            })
        }
    }else{
        return Promise.reject(error)
    }
    
})



export const ajax = (method="GET",url:string,data={}) => {
    if (method==="GET") {
        //console.log("geting......")
        return new Promise((resolve,reject) => {
            ajaxs.get(url,{params:data}).then(res => {resolve(res.data);})
            .catch(er => {reject(er.data)})
        })
    }else{
        //console.log("posting......")
        return new Promise((resolve,reject) => {
            ajaxs.post(url,data).then(res => {resolve(res.data)})
            .catch(err => {reject(err.data)})
        })
    }
}